package com.zhb.framework.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * JSON工具类
 */
public class JsonUtil {

    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 将model转换为json
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String toJson(T t){
        String json;
        try {
            json = OBJECT_MAPPER.writeValueAsString(t);
        }catch (Exception e){
            log.error("convert model to json failure ", e);
            throw new RuntimeException(e);
        }
        return json;
    }

    /**
     * 将json转为model
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> type){
        T t;
        try {
            t = OBJECT_MAPPER.readValue(json,type);
        }catch (Exception e){
            log.error("convert json to model failure ", e);
            throw new RuntimeException(e);
        }
        return t;
    }
}
